package cgserver

import (
	"cgs-server/internal/cgserver/embedfile"
	"cgs-server/internal/pkg/code"
	"cgs-server/internal/pkg/middleware"
	"cgs-server/internal/pkg/middleware/auth"
	"cgs-server/server"
	"cgs-server/server/routers"
	"git.mapchang.com/go/base/core"
	"git.mapchang.com/go/errors"
	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
	"mime"
	"net/http"

	// custom gin validators.
	_ "cgs-server/pkg/validator"
)

func initRouter(g *gin.Engine) {
	installMiddleware(g)
	installController(g)
}

func installMiddleware(g *gin.Engine) {
}

func installController(g *gin.Engine) *gin.Engine {

	// register custom mime-type
	_ = mime.AddExtensionType(".js", "application/javascript; charset=UTF-8")

	g.StaticFS("/Upload", http.Dir(viper.GetString("path.upload-dir")))
	g.StaticFS("/static", ioFS{
		prefix:     "static",
		FileSystem: http.FS(embedfile.Static),
	})

	g.Use(middleware.AccessTokenMiddleware)
	g.Use(middleware.ValidateTokenMiddlewareGin, middleware.SdkMiddleware)

	// Middlewares.
	jwtStrategy, _ := newJWTAuth().(auth.JWTStrategy)
	g.POST("/login", jwtStrategy.LoginHandler)
	g.POST("/logout", jwtStrategy.LogoutHandler)
	// Refresh time can be longer than token timeout
	g.POST("/refresh", jwtStrategy.RefreshHandler)

	//auto := newAutoAuth()
	g.NoRoute(func(c *gin.Context) {
		core.WriteResponse(c, errors.WithCode(code.ErrPageNotFound, "Page not found."), nil)
	})

	routers.Init()
	server.InitRoute()

	// todo add other routers

	return g
}

// ioFS 自定义的带有前缀补全的 FS
type ioFS struct {
	prefix string
	http.FileSystem
}

func (f ioFS) Open(name string) (http.File, error) {
	return f.FileSystem.Open(f.prefix + name)
}
